﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace theguineasyndrome
{
    class Goomba : Enemy
    {
        public Goomba(Level level, Texture2D texture, Vector2 position)
            : base(level, texture, position)
        {
            animation = new Animation(texture, new Vector2(87, 75), 50, true);
            rectangle.Width = (int)animation.Width;
            collisionRectangle = new Rectangle(13, 3, 60, 63);
            animation.setPosition(position);
        }

        public override void Update(GameTime gameTime)
        {
            if (!onTheFloor)
            {
                Center += new Vector2(0, (float)(direction * gameTime.ElapsedGameTime.TotalMilliseconds * 0.2));

                List<Utils.Pair<ObstacleElement, Rectangle>> collidingObstacles = level.getCollidingObstacles(getCollisionRectangle());
                if (collidingObstacles.Count > 0)
                {
                    float top = collidingObstacles[0].Second.Top;
                    foreach (Utils.Pair<ObstacleElement, Rectangle> collidingObstacle in collidingObstacles)
                    {
                        if (collidingObstacle.First.Top < top)
                            top = collidingObstacle.First.Top;
                    }
                    Bottom = top + (Height - collisionRectangle.Bottom) * 2;
                    onTheFloor = true;
                }
                animation.setPosition(Position);
            }
            else
            {
                if (level.isColliding(new Vector2(Center.X + (Width / 2 + 1) * direction, Bottom - 20)))
                {
                    direction *= -1;
                }
                else if (!level.isColliding(new Vector2(Center.X + (Width / 2 + 1) * direction, Bottom + 20)))
                {
                    direction *= -1;
                }
                Position += new Vector2((float)(gameTime.ElapsedGameTime.TotalMilliseconds * 0.15 * (double)direction), 0);
                animation.setPosition(Position);
            }
            animation.Update(gameTime);
        }

        public override void Draw(SpriteBatch spriteBatch, Camera camera)
        {
            if (direction < 0)
                animation.flip(true, false);

            else
                animation.flip(false, false);

            animation.Draw(spriteBatch, camera);
        }
    }
}
